<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>个人资料</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="text-center">
            <el-avatar 
              :size="120" 
              :src="userInfo.avatar ? getImageUrl(userInfo.avatar) : ''" 
              icon="UserFilled"
            />
            <div class="mt-20">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <el-button type="primary">更换头像</el-button>
              </el-upload>
            </div>
          </div>
        </el-col>
        
        <el-col :span="16">
          <el-descriptions title="基本信息" :column="1" border>
            <el-descriptions-item label="ID">{{ userInfo.id }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ userInfo.userName }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ userInfo.phone }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="userInfo.status === 1 ? 'success' : 'danger'">
                {{ userInfo.status === 1 ? '启用' : '停用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ userInfo.createTime }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ userInfo.updateTime }}</el-descriptions-item>
          </el-descriptions>
          
          <div class="mt-20">
            <el-button type="primary" @click="showPasswordDialog">修改密码</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      v-model="passwordDialogVisible"
      width="400px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            placeholder="请输入原密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码" 
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码" 
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitPasswordForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo, updatePassword, saveOrUpdateAdmin } from '@/api/user'

// 用户信息
const userInfo = ref({
  id: '',
  userName: '',
  avatar: '',
  phone: '',
  status: 1,
  createTime: '',
  updateTime: ''
})

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/api/file/download?fileName=${imagePath}`
}

// 上传URL
const uploadUrl = '/api/file/uploadImage/user'

// 加载状态
const loading = ref(false)
const submitLoading = ref(false)

// 密码表单对话框可见性
const passwordDialogVisible = ref(false)
const passwordFormRef = ref(null)

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 4, message: '密码长度不能小于4位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 初始化数据
onMounted(async () => {
  await fetchUserInfo()
})

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true
  try {
    const res = await getUserInfo()
    if (res.code === 200) {
      userInfo.value = res.data
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 上传前验证
const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('头像只能是JPG或PNG格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleAvatarSuccess = async (response, file) => {
  if (response.code === 200) {
    try {
      // 更新本地头像显示
      userInfo.value.avatar = response.data
      
      // 调用API更新用户信息
      await saveOrUpdateAdmin({
        id: userInfo.value.id,
        avatar: response.data
      })
      
      ElMessage.success('头像上传成功')
    } catch (error) {
      console.error('更新头像信息失败:', error)
      ElMessage.error('头像上传成功，但更新信息失败')
    }
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

// 显示密码对话框
const showPasswordDialog = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordDialogVisible.value = true
}

// 提交密码表单
const submitPasswordForm = () => {
  passwordFormRef.value.validate(async valid => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      await updatePassword({
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword
      })
      
      ElMessage.success('密码修改成功')
      passwordDialogVisible.value = false
    } catch (error) {
      console.error('密码修改失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text-center {
  text-align: center;
}

.mt-20 {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

.avatar-uploader {
  margin-top: 10px;
}
</style> 